// 封装ajax，直接传入大对象
function ajax(options) {
  let det = {
    url: "",
    method: "GET",
    async: true,
    data: {},
    headers: {},
    success: function () {
      console.log("成功");
    },
    error: function () {
      console.log("失败");
    },
  };

  let { url, method, async, data, headers, success, error } = {
    ...det,
    ...options,
  };

  let xhr = new XMLHttpRequest();
  let mes = "";
  xhr.open(method, url, async);

  let pat = /2\d\d/;

  //分类讨论,post，put，patch需要传mes
  //判断头
  if (headers["Content-Type"] && headers["Content-Type"].includes("json")) {
    xhr.setRequestHeader("Content-Type", headers["Content-Type"]);
    mes = JSON.stringify(data);
  }

  xhr.onload = function () {
    if (pat.test(xhr.status)) {
      success(xhr.response);
    } else {
      error();
    }
  };

  xhr.send(mes);
}

// promise封装ajax
function p_ajax(options) {
  return new Promise((resolve, reject) => {
    ajax({
      ...options,
      success(res) {
        resolve(res);
      },
      error(res) {
        reject(res);
      },
    });
  });
}
